import datetime

from pymysql.cursors import DictCursor
from pool_context_manager import ConnectionPool


class Field:
    pass


class Model:
    pass


class Author(Model):
    
    __table__ = 'author'

    id = Field()
    name = Field()
    country = Field()

    def __init__(self, **kwargs):
        self.id = kwargs.get('id')
        self.name = kwargs.get('name')
        self.country = kwargs.get('country')


class DB:
    def __init__(self, **kwargs):
        self.pool = ConnectionPool(**kwargs)

    def insert(self, instance):
        if not isinstance(instance, Model):
            raise Exception('{} is not instance of Model.'.format(instance.__class__))
        fields = []
        values = []
        # 只有字段正确时，才操作数据库
        for field_name, field in instance.__class__.__dict__.items():
            if isinstance(field, Field):
                v = getattr(instance, field_name)
                if v is not None and isinstance(v, (int, float, str, datetime.datetime)):
                    fields.append('`{}`'.format(field_name))
                    if isinstance(v, (int, float)):
                        values.append(str(v))
                    if isinstance(v, str):
                        values.append('"{}"'.format(v))
                    if isinstance(v, datetime.datetime):
                        values.append('"{}"'.format(v.isoformat()))
        sql = '''insert into `{}`({}) values({})'''.format(
            instance.__table__,
            ', '.join(fields),
            ', '.join(values)
        )
        print(sql)
        with self.pool() as cur:
            cur.execute(sql)


if __name__ == '__main__':
    db = DB(host='127.0.0.1',
            port=3306,
            user='root',
            password='123456',
            database='demo',
            cursorclass=DictCursor
    )
    author = Author(name='cc', country='China')
    author.haha = 'haha'
    db.insert(author)